package com.molyfun.parents.activity.schoolonline.homework;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseChoosePicActivity;
import com.molyfun.parents.activity.common.attachment.AttachmentView;
import com.molyfun.parents.activity.common.attachment.AttachmentViewer;
import com.molyfun.parents.activity.schoolonline.homework.view.CompleteProcessView;
import com.molyfun.parents.activity.schoolonline.homework.view.VoiceInputView;
import com.molyfun.parents.fragment.dialog.CommonEnsureDialogFragment;
import com.molyfun.parents.fragment.dialog.CommonInputDialogFragment;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.bean.CommitHomeWorkRequest;
import com.molyfun.parents.rest.bean.HomeWorkResponse;
import com.molyfun.parents.rest.bean.MediaobjectlistBean;
import com.molyfun.parents.utils.JsonParser;
import com.molyfun.parents.utils.NetWorkUtil;
import com.molyfun.parents.utils.UIUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:11/2/16.
 * 家庭作业详情页接口
 */
public class HomeWorkDetailActivity extends BaseChoosePicActivity implements View.OnClickListener, VoiceInputView.OnVoiceInputCallback, AttachmentView.AttachmentAddCallback{

    private static final String FLAG_HOMEWORK_BEAN = "homework_bean";

    @InjectView(R.id.base_title_left)
    ImageView mBackBtn;
    @InjectView(R.id.submit)
    TextView mCommit;
    @InjectView(R.id.base_title)
    TextView mTitle;

    @InjectView(R.id.content)
    TextView mContent;
    @InjectView(R.id.complete_process_view)
    CompleteProcessView completeProcessView;
//    @InjectView(R.id.voice_input_view)
//    VoiceInputView mVoiceInputView;
    @InjectView(R.id.voice_input_edt)
    TextView mVoiceInputEdt;
    @InjectView(R.id.attachment_view)
    AttachmentView mAttachmentView;

//    @InjectView(R.id.recyclerView)
//    RecyclerView mRecyclerView;
    @InjectView(R.id.homework_detail_attachment_list)
    AttachmentViewer mHomeWorkList;

//    LinearLayoutManager mLinearLayoutManager;
//    CourseDetailAdapter courseDetailAdapter;

    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();

    // 语音听写对象
    private SpeechRecognizer mIat;

    HomeWorkResponse.HomeWorkBean mHomeWorkBean;

    public static void startActivity(Context content, HomeWorkResponse.HomeWorkBean homeWorkBean){
        Intent intent = new Intent();
        intent.setClass(content, HomeWorkDetailActivity.class);
        intent.putExtra(FLAG_HOMEWORK_BEAN, homeWorkBean);
        content.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homework_detail);

        ButterKnife.inject(this);
        getSupportActionBar().setTitle("");

        mTitle.setText("作业详情");
        mCommit.setText("完成");

        initIntent();

        mIat = SpeechRecognizer.createRecognizer(HomeWorkDetailActivity.this, mInitListener);
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");

        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, "1000");

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "1");


        mBackBtn.setOnClickListener(this);
        mCommit.setOnClickListener(this);
//        mVoiceInputView.setOnVoiceInputCallback(this);
        mAttachmentView.setAttachmentAddCallback(this);

//        mRecyclerView.setHasFixedSize(true);
//        mLinearLayoutManager = new LinearLayoutManager(this);
//        mRecyclerView.setLayoutManager(mLinearLayoutManager);
//
//        courseDetailAdapter = new CourseDetailAdapter(this);
//        mRecyclerView.setAdapter(courseDetailAdapter);

        if(mHomeWorkBean != null && mHomeWorkBean.getGallerymediaobjectlist() != null && mHomeWorkBean.getGallerymediaobjectlist().size() > 0){
            mHomeWorkList.initData(mHomeWorkBean.getGallerymediaobjectlist());
//            courseDetailAdapter.refreshData(mHomeWorkBean.getGallerymediaobjectlist());
        }else{
            mHomeWorkList.setVisibility(View.GONE);
        }

    }

    private void initIntent(){
        mHomeWorkBean = getIntent().getParcelableExtra(FLAG_HOMEWORK_BEAN);
        if(mHomeWorkBean != null){
            mContent.setText(mHomeWorkBean.getContent());
            completeProcessView.initData(mHomeWorkBean.getResultlist());
            mAttachmentView.addList(mHomeWorkBean.getMediaobjectlist());
            mVoiceInputEdt.setText(mHomeWorkBean.getComment());
            mTitle.setText(mHomeWorkBean.getName());

        }

        mVoiceInputEdt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new CommonInputDialogFragment.CommonInputDialogBuilder(mHomeWorkBean == null? "" : mHomeWorkBean.getComment())
                        .setOnCommonInputCallback(new CommonInputDialogFragment.OnCommonInputCallback() {
                            @Override
                            public void onInputConfirm(String content) {
                                mVoiceInputEdt.setText(content);
                                mHomeWorkBean.setComment(content);
                            }
                        })
                        .build(getSupportFragmentManager().beginTransaction());

            }
        });
    }

    @Override
    public void onVoiceInput() {
        // 不显示听写对话框
        int ret = mIat.startListening(mRecognizerListener);
        if (ret != ErrorCode.SUCCESS) {
            toast("听写失败,错误码：" + ret);
        } else {
//            showTip(getString(R.string.text_begin));
        }
    }

    @Override
    public void onAttachmentAdd() {
        if(!NetWorkUtil.isNetworkAvailable(this)){
            new CommonEnsureDialogFragment.CommonEnsureDialogBuilder("没有网络，请检查网络")
                    .build(getSupportFragmentManager().beginTransaction());
            return;
        }
//        choosePic();
        chooseMedia();
    }

    /**
     * 听写监听器。
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
            toast("开始说话");
        }

        @Override
        public void onError(SpeechError error) {
            // Tips：
            // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
            // 如果使用本地功能（语记）需要提示用户开启语记的录音权限。
            toast(error.getPlainDescription(true));
        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            toast("结束说话");
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {

            printResult(results);
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
//            toast("当前正在说话，音量大小：" + volume);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };

    private void printResult(RecognizerResult results) {
        mIatResults.clear();
        String text = JsonParser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }

        mVoiceInputEdt.setText(resultBuffer.toString());
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.base_title_left:
                finish();
                break;
            case R.id.submit:
                if(!NetWorkUtil.isNetworkAvailable(this)){
                    new CommonEnsureDialogFragment.CommonEnsureDialogBuilder("没有网络，请检查网络")
                            .build(getSupportFragmentManager().beginTransaction());
                    return;
                }
                if(TextUtils.isEmpty(completeProcessView.getChooseId())){
                    toast("请选择完成度");
                    return;
                }

                showProgressDialog();
                CommitHomeWorkRequest commitHomeWorkRequest = new CommitHomeWorkRequest();
                commitHomeWorkRequest.setId(mHomeWorkBean.getId());
                commitHomeWorkRequest.setResult(completeProcessView.getChooseId());
                commitHomeWorkRequest.setComment(mVoiceInputEdt.getText().toString().trim());
                commitHomeWorkRequest.setMediaobjectlist(mAttachmentView.getAttachment());
                Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().commitHomeWork(commitHomeWorkRequest);
                call.enqueue(new Callback<BaseResponse>() {
                    @Override
                    public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                        dismissProgressDialog();
                        if(response.body().getCode() == 200){
                            UIUtils.showToast(HomeWorkDetailActivity.this, "提交成功");
                            finish();
                        }else{
                            UIUtils.showToast(HomeWorkDetailActivity.this, response.body().getMsg());
                        }

                    }

                    @Override
                    public void onFailure(Call<BaseResponse> call, Throwable t) {
                        dismissProgressDialog();
                    }
                });

                break;
        }
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                toast("初始化失败，错误码：" + code);
            }
        }
    };

    @Override
    public void onPictureUploadSuccess(String localPath, String smallUrl, String originalUrl) {
        MediaobjectlistBean mediaAttachment = new MediaobjectlistBean();
        mediaAttachment.setUrl(originalUrl);
        mediaAttachment.setType(1);
        mAttachmentView.addAttachment(mediaAttachment);
    }

    public void onPictureUploadBegin(String path, String UploadPath){

    }

    @Override
    public void onPictureUploadFailed(String path, String UploadPath) {
        toast("图片上传失败");
    }

    @Override
    public void onVideoUploadSuccess(String cover, String path) {
        MediaobjectlistBean mediaAttachment = new MediaobjectlistBean();
        mediaAttachment.setUrl(path);
        mediaAttachment.setType(2);
        mAttachmentView.addAttachment(mediaAttachment);
    }

    @Override
    public String getAttachmentFolder() {
        return "homework";
    }
}
